package com.itheima.tcp.socketFile1;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

public class FileUpload implements Runnable {
    private Socket socket;
    public FileUpload(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedOutputStream bos = null;
        try {
            BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
            // BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
//            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("day16_网络编程\\ServiceDir\\"+ System.currentTimeMillis() + ".jpg"));
            bos = new BufferedOutputStream(new FileOutputStream("day16_网络编程\\ServiceDir\\"+ UUID.randomUUID().toString() + ".jpg"));
            int b;
            while ((b = bis.read()) != -1){
                bos.write(b);
            }
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bw.write("上传成功");
            bw.newLine();
            bw.flush();


        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null){

                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
